package com.zjpavt.client.command.offlinecommand;

import com.zjpavt.client.util.LoggerUtil;
import com.zjpavt.client.util.MathUtil;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 离线指令实体类
 *
 * @author cjp
 */
public class OfflineCommandBean implements Comparable<OfflineCommandBean> {

    /**
     * 离线指令触发时间
     */
    private Date date;
    /**
     * 离线指令（16进制）
     */
    private String commandHex;


    public OfflineCommandBean(Date date, String commandHex) {
        this.date = date;
        this.commandHex = commandHex;
    }

    /**
     * @return 获取指令触发
     */
    public Date getDate() {
        return date;
    }

    /**
     * @return 16进制指令
     */
    public String getCommandHex() {
        return commandHex;
    }

    /**
     * @return 2进制指令
     */
    public String getCommand() {
        String res = null;
        try {
            res = MathUtil.HexStringToBinaryString(getCommandHex());
        } catch (NumberFormatException e) {
            LoggerFactory.getLogger(OfflineCommandBean.class).error(LoggerUtil.convertException2String(e));
        }
        return res;
    }

    @Override
    public String toString() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder sb = new StringBuilder();
        sb.append(simpleDateFormat.format(date))
        .append(" ")
        .append(commandHex);
        return sb.toString();
    }

    /**
     * 	时间顺序排列
     */
    @Override
    public int compareTo(OfflineCommandBean o) {
        return (this.getDate().getTime() - o.getDate().getTime()) > 0 ? 1 : -1;
    }

    public boolean isOutOfDate() {
        return System.currentTimeMillis() > getDate().getTime();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof OfflineCommandBean)) {
            return false;
        }
        OfflineCommandBean bean = (OfflineCommandBean) obj;
        return bean.getDate().getTime() == this.getDate().getTime() && bean.getCommandHex().equals(this.getCommandHex());
    }
}
